<template>
  <div class="flex" :ref="`comment-${comment.id}`">
    <router-link
      :to="`/users/${comment.author.id}`"
      target="_blank"
      class="m-l-16 m-r-10 p-t-22 shrink-0"
    >
      <el-avatar :src="comment.author.avatar" />
    </router-link>
    <div class="p-b-14 p-t-22 m-t-10 flex-1 con">
      <router-link
        :to="`/users/${comment.author.id}`"
        target="_blank"
        class="p-b-4 title link el-link--primary"
        v-text="comment.author.nickname"
      />
      <div class="p-y-2">
        <div v-html="emojiFormat(comment.content)"></div>
      </div>
      <div class="info f-mini">
        <timeago2 :date-time="comment.created_at" class="m-r-16" />
        <span class="link info el-link--primary" @click="replyClick(comment)">回复</span>
      </div>
      <comment-sub-item
        v-for="item in comments"
        :key="item.id"
        :comment="item"
        @replyClick="replyClick"
      />
      <template v-if="loading">
        <div class="info-deep f-mini">loading...</div>
      </template>
      <template v-else>
        <div v-if="!loadedSubs && comment.subsCount > num" class="flex info-deep f-mini">
          共{{ comment.subsCount }}条回复，
          <span class="link el-link--primary" @click="moreComments">点击查看</span>
        </div>
        <div v-if="loadedSubs && pagination.pageCount > 1" class="flex align-items-center">
          <span class="f-mini">共{{ pagination.pageCount }}页</span>
          <el-pagination
            small
            layout="prev, pager, next"
            hide-on-single-page
            prev-text="上一页"
            next-text="下一页"
            :current-page="pagination.currentPage"
            :page-count="pagination.pageCount"
            @current-change="loadSubComments"
            class="btn-prev-auto-hide f-mini"
          />
        </div>
      </template>
      <reply v-if="replyShow" ref="reply" :floor-id="comment.id" @replied="replied" />
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import EmojiMixin from '@/components/emoji/emoji-mixin';
import { formatComments } from '@/components/shared/comments/format';
import CommentSubItem from './comment-sub-item';
import Reply from './reply';

export default {
  name: 'comment-item',
  mixins: [EmojiMixin],
  components: { CommentSubItem, Reply },
  props: {
    comment: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      num: 3, // 默认加载楼中楼的数量
      loading: false,
      comments: [],
      pagination: {},
      loadedSubs: false,
    };
  },
  computed: {
    ...mapState('comments', { activeComment: 'activeComment' }),
    // parentId 是楼中楼特有，点击“回复”按钮时会改变这个值。主楼点回复时没有这个值的
    replyShow() {
      const receiverCommentId = this.activeComment.parentId || this.activeComment.id;
      return receiverCommentId === this.comment.id;
    },
    // 消息提醒跳转过来的数据
    queryComment() {
      const query = this.$route.query;
      return {
        page: query.page,
        commentId: query.comment_id,
        subPage: query.sub_page,
        subCommentId: query.sub_comment_id,
      };
    },
  },
  created() {
    // 如果不是定位到当前楼中楼（没有楼中楼页码），加载三楼
    if (this.comment.subsCount && !this.queryComment.subPage) {
      this.loadSubComments(undefined, this.num);
    } else {
      this.loadSubComments(this.queryComment.subPage);
    }
  },
  mounted() {
    // 检测到这当前item时，定位到这里
    if (this.queryComment.commentId === this.comment.id) {
      this.$refs[`comment-${this.comment.id}`].scrollIntoView({ block: 'center' });
    }
  },
  methods: {
    ...mapActions('comments', { setActiveComment: 'updateActiveComment' }),
    // 点击回复
    replyClick(comment) {
      this.setActiveComment(comment);
      if (this.replyShow) {
        this.$nextTick(() => this.$refs.reply.onFocus());
      }
    },
    // 回复了评论
    replied(comment) { this.comments.unshift(comment); },
    // 加载楼中楼
    loadSubComments(page = 1, number = 10) {
      this.loading = true;
      this.$api.comments.subIndex({
        commentId: this.comment.id,
        page,
        number,
        order: this.queryComment.subPage ? 'asc' : 'desc',
      }).then((res) => {
        this.comments = formatComments(res.data);
        this.pagination.currentPage = res.kaminari.current_page;
        this.pagination.pageCount = res.kaminari.total_pages;
      }).catch(() => {})
        .then(() => { this.loading = false; });
    },
    // 点击查看更多回复
    moreComments() {
      this.loadedSubs = true;
      this.loadSubComments();
    },
  },
};
</script>

<style></style>
